<template>
	<div class="json-editor">
		<textarea ref="textarea"></textarea>
	</div>
</template>

<script>	
	LinkCssOrScss("/vue/libs/codemirror/addon/lint/lint.css");
	LinkCssOrScss("/vue/libs/codemirror/lib/codemirror.css");
	LinkCssOrScss("/vue/libs/codemirror/theme/rubyblue.css");

	Promise.all([
		LoadScriptThen("/vue/libs/jsonlint/lib/jsonlint.js"),
		LoadScriptThen("/vue/libs/codemirror/lib/codemirror.js"),
		LoadScriptThen("/vue/libs/codemirror/mode/javascript/javascript.js"),
		LoadScriptThen("/vue/libs/codemirror/addon/lint/lint.js"),
		LoadScriptThen("/vue/libs/codemirror/addon/lint/json-lint.js")
	]).then(() => {
		module.exports = {
			name: 'JsonEditor',
			props: ['value'],
			data() {
				return {
					jsonEditor: false
				}
			},
			watch: {
				value(value) {
					const editorValue = this.jsonEditor.getValue()
					if (value !== editorValue) {
						this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
					}
				}
			},
			mounted() {
				this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
					lineNumbers: true,
					mode: 'application/json',
					gutters: ['CodeMirror-lint-markers'],
					theme: 'rubyblue',
					lint: true
				})

				this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
				this.jsonEditor.on('change', cm => {
					this.$emit('changed', cm.getValue())
					this.$emit('input', cm.getValue())
				})
			},
			methods: {
				getValue() {
					return this.jsonEditor.getValue()
				}
			}
		}
	});
</script>

<style scoped>
	.json-editor {
		height: 100%;
		position: relative;
	}

		.json-editor > .CodeMirror {
			height: auto;
			min-height: 300px;
		}

		.json-editor > .CodeMirror-scroll {
			min-height: 300px;
		}

		.json-editor > .cm-s-rubyblue span.cm-string {
			color: #F08047;
		}
</style>
